package com.qf.controller;

import com.qf.enums.ExceptionEnums;
import com.qf.exception.ExamException;
import com.qf.util.UploadUtil;
import com.qf.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.persistence.SqlResultSetMapping;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/upload")
public class AliYunUploadController {
    private final String PIC_DIR="image";
    private final String APK_DIR = "apks";
    private final String APK_TYPE_NAME=".apk";
    private final long MAX_SIZE=5243880;
    @Autowired
    private UploadUtil uploadUtil;
    @Value("${pic.types}")
    private String types;
    @RequestMapping("/picc")
    public ResultVo pic(MultipartFile file) throws IOException {
//首先校验图片不能为空
        if(file==null){
            log.info("图片不能为空");
            throw new ExamException(ExceptionEnums.PIC_NULL);
        }
//校验大小
        if(file.getSize()>MAX_SIZE){
            log.info("图片过大了");
            throw new ExamException(ExceptionEnums.PICFILE_BIG);
        }
        //校验类别
        boolean falg=false;
        for (String type : types.split(",")) {
            if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                falg=true;
                break;
            }
        }
        if(!falg){
            log.info("【图片类型不匹配】,file={}",file);
            throw new ExamException(ExceptionEnums.PICFILE_TYPE);
        }
        //判断是否损坏
        BufferedImage read = null;
        try {
            read = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(read==null){
            log.info("【图片已经损坏】图片已损坏");
            throw new ExamException(ExceptionEnums.BAD);
        }
        //起一个新的名字
        String prefixname= UUID.randomUUID().toString();
        String suffixname=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newName=prefixname+suffixname;
        //调用阿里云的appOs存储图片
        //保存到OSS上 获得访问路径
        String src=uploadUtil.uploadPic(APK_DIR+"/"+newName,file.getInputStream());
        //6. 响应.

        return new ResultVo(0,"",src);
    }}
